package com.oocl.consumer.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQQueue;

import com.oocl.connection.MQConnection;
import com.oocl.consumer.MsgConsumer;
import com.oocl.dao.BookDao;
import com.oocl.manager.MsgConsumerManager;
import com.oocl.pojo.Book;
import com.oocl.util.JacksonUtil;

public class MsgConsumerImpl implements MsgConsumer {

	BookDao bookDao;

	Session sen = null;
	MessageConsumer consumer;
	List<Book> bookList = new ArrayList<Book>();
	

	public MsgConsumerImpl(BookDao bookDao) {
		this.bookDao = bookDao;
	}

	@Override
	public void onLine() {
		MQConnection.getInstance().start();
		this.sen = MQConnection.getInstance().getSession();
		try {
			this.consumer = sen.createConsumer(new ActiveMQQueue("jasper"));
			this.consumer.setMessageListener(new MessageListener() {

				@Override
				public void onMessage(Message message) {
					try {
						TextMessage textMessage = (TextMessage) message;
						String jsonStr = textMessage.getText();
						System.out.println("接收到的json ： " + jsonStr);
						
						// /处理json串，并存储到Oracle
						receiveMsgAndDeal(jsonStr);
						new Thread(){
							public void run() {
								MsgConsumerManager.count++;
							};
						}.start();
						System.out.println("count = "+ MsgConsumerManager.count);
						///最后告诉说完成了
						message.acknowledge();
						
						
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}

			});
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean receiveMsgAndDeal(String msg) {

		// 首先，解析json数据
		final Book book = JacksonUtil.fromJsonToObject(msg, Book.class);
		
		///批量插入数据库
		bookList.add(book);
		
		if(bookList.size()>=40){
			bookDao.addBooks(bookList);
			bookList.clear();
		}
		
//		///单个插入数据库
//		bookDao.addBook(book);
//		
		return true;
	}

	@Override
	public void offLine() {
		try {
			if(bookList.size()>=0){
				bookDao.addBooks(bookList);
				bookList.clear();
			}
			this.consumer.close();// /是流，需要关
			this.sen.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
